// 故事管理器
class StoryManager {
    constructor() {
        this.currentStory = null;
        this.storyHistory = [];
        this.choiceHistory = [];
        this.flags = {};
        this.variables = {};
        
        this.init();
    }

    init() {
        // 绑定事件
        this.bindEvents();
        
        // 初始化故事数据
        this.initializeStoryData();
    }

    bindEvents() {
        // 监听语言切换事件
        window.addEventListener('languageChanged', () => {
            this.updateStoryDisplay();
        });

        // 监听场景切换事件
        window.addEventListener('sceneChanged', (e) => {
            this.onSceneChanged(e.detail);
        });
    }

    initializeStoryData() {
        // 扩展故事数据，添加更多内容
        this.extendedStoryData = {
            // 角色数据
            characters: {
                protagonist: {
                    name: "研究员",
                    description: "一名专注于量子物理研究的年轻科学家",
                    traits: []
                },
                ai_assistant: {
                    name: "ARIA",
                    description: "实验室的AI助手",
                    traits: ["helpful", "analytical"]
                }
            },

            // 物品/设备数据
            items: {
                quantum_device: {
                    name: "量子共振设备",
                    description: "一台能够操控时空的神秘设备",
                    status: "unknown"
                },
                data_pad: {
                    name: "数据终端",
                    description: "显示实验数据的终端设备",
                    status: "active"
                }
            },

            // 世界状态
            worldState: {
                timeline: "original",
                lab_status: "operational",
                time_anomaly_level: 0,
                discovery_progress: 0
            },

            // 扩展的场景数据
            extendedScenes: {
                // 添加更多过渡场景
                "chapter1_scene1b": {
                    id: "chapter1_scene1b",
                    title: "深入调查",
                    content: "你决定先调查一下这个异常现象的来源。查看实验日志，你发现在过去几天里，设备的量子场强度一直在缓慢上升，而今晚似乎达到了临界点...",
                    image: "scene-img-investigation",
                    choices: [
                        {
                            id: "choice1b_1",
                            text: "查看更详细的历史数据",
                            leads_to: "chapter1_scene2a",
                            stats: { scientific: 1 }
                        },
                        {
                            id: "choice1b_2",
                            text: "尝试联系其他研究员",
                            leads_to: "chapter1_scene2d",
                            stats: { survival: 1 }
                        }
                    ]
                },

                "chapter1_scene2d": {
                    id: "chapter1_scene2d",
                    title: "寻求帮助",
                    content: "你尝试联系其他研究员，但发现通讯系统似乎受到了某种干扰。电话里只能听到奇怪的电子音，而网络连接也变得不稳定。看来你只能独自面对这个问题了...",
                    image: "scene-img-communication",
                    choices: [
                        {
                            id: "choice2d_1",
                            text: "继续尝试其他通讯方式",
                            leads_to: "chapter1_scene3g",
                            stats: { survival: 1 }
                        },
                        {
                            id: "choice2d_2",
                            text: "放弃求助，独自处理",
                            leads_to: "chapter1_scene2b",
                            stats: { explorer: 1 }
                        }
                    ]
                },

                "chapter1_scene3g": {
                    id: "chapter1_scene3g",
                    title: "意外的联系",
                    content: "当你尝试使用紧急通讯频道时，竟然收到了一个来自'未来'的信号。声音听起来很像你自己，警告说不要触碰量子设备。这是时空的扭曲，还是某种恶作剧？",
                    image: "scene-img-future-signal",
                    isEnding: true,
                    endingType: "time_paradox"
                }
            }
        };
    }

    // 获取角色信息
    getCharacter(characterId) {
        return this.extendedStoryData.characters[characterId] || null;
    }

    // 获取物品信息
    getItem(itemId) {
        return this.extendedStoryData.items[itemId] || null;
    }

    // 获取世界状态
    getWorldState() {
        return this.extendedStoryData.worldState;
    }

    // 更新世界状态
    updateWorldState(updates) {
        Object.assign(this.extendedStoryData.worldState, updates);
        this.onWorldStateChanged();
    }

    // 设置故事标志
    setFlag(flagName, value) {
        this.flags[flagName] = value;
        this.onFlagChanged(flagName, value);
    }

    // 获取故事标志
    getFlag(flagName, defaultValue = false) {
        return this.flags.hasOwnProperty(flagName) ? this.flags[flagName] : defaultValue;
    }

    // 设置故事变量
    setVariable(varName, value) {
        this.variables[varName] = value;
        this.onVariableChanged(varName, value);
    }

    // 获取故事变量
    getVariable(varName, defaultValue = null) {
        return this.variables.hasOwnProperty(varName) ? this.variables[varName] : defaultValue;
    }

    // 记录选择历史
    recordChoice(choiceId, sceneId, timestamp = Date.now()) {
        const choiceRecord = {
            choiceId,
            sceneId,
            timestamp,
            worldState: { ...this.extendedStoryData.worldState },
            flags: { ...this.flags },
            variables: { ...this.variables }
        };

        this.choiceHistory.push(choiceRecord);
        this.onChoiceRecorded(choiceRecord);
    }

    // 获取选择历史
    getChoiceHistory() {
        return [...this.choiceHistory];
    }

    // 分析玩家的选择倾向
    analyzePlayerTendencies() {
        if (this.choiceHistory.length === 0) {
            return null;
        }

        const analysis = {
            totalChoices: this.choiceHistory.length,
            tendencies: {
                scientific: 0,
                explorer: 0,
                survival: 0
            },
            patterns: {},
            recommendations: []
        };

        // 统计选择倾向
        this.choiceHistory.forEach(choice => {
            // 这里需要从游戏引擎获取选择的统计信息
            // 暂时简化处理
        });

        // 分析选择模式
        analysis.patterns = this.analyzeChoicePatterns();

        // 生成推荐
        analysis.recommendations = this.generateRecommendations(analysis);

        return analysis;
    }

    analyzeChoicePatterns() {
        const patterns = {
            quickDecision: 0, // 快速决策
            cautiousDecision: 0, // 谨慎决策
            consistentStyle: 0, // 一致性风格
            explorationLevel: 0 // 探索程度
        };

        // 分析决策速度、一致性等
        for (let i = 1; i < this.choiceHistory.length; i++) {
            const timeDiff = this.choiceHistory[i].timestamp - this.choiceHistory[i-1].timestamp;
            if (timeDiff < 10000) { // 10秒内
                patterns.quickDecision++;
            } else if (timeDiff > 30000) { // 30秒以上
                patterns.cautiousDecision++;
            }
        }

        return patterns;
    }

    generateRecommendations(analysis) {
        const recommendations = [];

        if (analysis.tendencies.scientific > analysis.tendencies.explorer) {
            recommendations.push("你展现出了科学家的理性思维，尝试更多冒险选择可能会有意外收获");
        }

        if (analysis.tendencies.survival > 2) {
            recommendations.push("你很重视安全，但有时勇敢一点可能会发现新的可能性");
        }

        if (analysis.patterns.quickDecision > analysis.patterns.cautiousDecision) {
            recommendations.push("你的决策很快速，偶尔深思熟虑可能会有不同的结果");
        }

        return recommendations;
    }

    // 生成故事摘要
    generateStorySummary() {
        const summary = {
            currentProgress: this.calculateProgress(),
            keyChoices: this.getKeyChoices(),
            characterDevelopment: this.analyzeCharacterDevelopment(),
            worldChanges: this.getWorldChanges(),
            unlockedContent: this.getUnlockedContent()
        };

        return summary;
    }

    calculateProgress() {
        // 基于选择数量和解锁内容计算进度
        const totalPossibleChoices = 20; // 假设总共有20个主要选择点
        const currentChoices = this.choiceHistory.length;
        
        return {
            percentage: Math.min((currentChoices / totalPossibleChoices) * 100, 100),
            choicesMade: currentChoices,
            totalChoices: totalPossibleChoices
        };
    }

    getKeyChoices() {
        // 返回对故事影响重大的选择
        return this.choiceHistory.filter(choice => 
            choice.choiceId.includes('key_') || 
            choice.choiceId.includes('major_')
        );
    }

    analyzeCharacterDevelopment() {
        // 分析角色发展轨迹
        const protagonist = this.getCharacter('protagonist');
        if (!protagonist) return null;

        const development = {
            traits: [...protagonist.traits],
            growthAreas: [],
            relationships: {}
        };

        // 基于选择历史分析角色成长
        this.choiceHistory.forEach(choice => {
            // 根据选择类型添加角色特质
            if (choice.choiceId.includes('scientific')) {
                if (!development.traits.includes('analytical')) {
                    development.traits.push('analytical');
                }
            }
            if (choice.choiceId.includes('explorer')) {
                if (!development.traits.includes('adventurous')) {
                    development.traits.push('adventurous');
                }
            }
            if (choice.choiceId.includes('survival')) {
                if (!development.traits.includes('cautious')) {
                    development.traits.push('cautious');
                }
            }
        });

        return development;
    }

    getWorldChanges() {
        // 追踪世界状态的变化
        const changes = [];
        
        // 这里可以比较初始世界状态和当前状态
        const initialState = {
            timeline: "original",
            lab_status: "operational",
            time_anomaly_level: 0,
            discovery_progress: 0
        };

        const currentState = this.getWorldState();
        
        Object.keys(currentState).forEach(key => {
            if (currentState[key] !== initialState[key]) {
                changes.push({
                    property: key,
                    from: initialState[key],
                    to: currentState[key]
                });
            }
        });

        return changes;
    }

    getUnlockedContent() {
        // 返回已解锁的内容
        const unlocked = {
            scenes: [],
            characters: [],
            items: [],
            endings: []
        };

        // 基于选择历史和标志确定解锁的内容
        this.choiceHistory.forEach(choice => {
            if (!unlocked.scenes.includes(choice.sceneId)) {
                unlocked.scenes.push(choice.sceneId);
            }
        });

        return unlocked;
    }

    // 文本处理和本地化
    processStoryText(text, context = {}) {
        // 处理文本中的变量替换
        let processedText = text;

        // 替换变量 {variable_name}
        Object.keys(this.variables).forEach(varName => {
            const regex = new RegExp(`{${varName}}`, 'g');
            processedText = processedText.replace(regex, this.variables[varName]);
        });

        // 替换角色名称 {character.name}
        Object.keys(this.extendedStoryData.characters).forEach(charId => {
            const character = this.extendedStoryData.characters[charId];
            const regex = new RegExp(`{${charId}.name}`, 'g');
            processedText = processedText.replace(regex, character.name);
        });

        // 处理条件文本 [if flag_name]text[/if]
        processedText = this.processConditionalText(processedText);

        return processedText;
    }

    processConditionalText(text) {
        const conditionalRegex = /\[if\s+(\w+)\](.*?)\[\/if\]/g;
        
        return text.replace(conditionalRegex, (match, flagName, content) => {
            return this.getFlag(flagName) ? content : '';
        });
    }

    // 事件处理
    onSceneChanged(sceneData) {
        this.currentStory = sceneData;
        
        // 记录场景历史
        this.storyHistory.push({
            sceneId: sceneData.sceneId || sceneData.id,
            timestamp: Date.now(),
            worldState: { ...this.extendedStoryData.worldState }
        });

        // 更新世界状态
        this.updateWorldStateBasedOnScene(sceneData);
    }

    onChoiceRecorded(choiceRecord) {
        // 当记录选择时触发
        console.log('选择已记录:', choiceRecord);
        
        // 可以在这里触发自定义事件
        window.dispatchEvent(new CustomEvent('storyChoiceRecorded', {
            detail: choiceRecord
        }));
    }

    onFlagChanged(flagName, value) {
        console.log(`标志变化: ${flagName} = ${value}`);
        
        // 触发标志变化事件
        window.dispatchEvent(new CustomEvent('storyFlagChanged', {
            detail: { flagName, value }
        }));
    }

    onVariableChanged(varName, value) {
        console.log(`变量变化: ${varName} = ${value}`);
        
        // 触发变量变化事件
        window.dispatchEvent(new CustomEvent('storyVariableChanged', {
            detail: { varName, value }
        }));
    }

    onWorldStateChanged() {
        console.log('世界状态已更新:', this.extendedStoryData.worldState);
        
        // 触发世界状态变化事件
        window.dispatchEvent(new CustomEvent('worldStateChanged', {
            detail: this.extendedStoryData.worldState
        }));
    }

    updateWorldStateBasedOnScene(sceneData) {
        // 根据场景更新世界状态
        if (sceneData.id && sceneData.id.includes('lab')) {
            this.updateWorldState({ lab_status: 'active' });
        }
        
        if (sceneData.isEnding) {
            this.updateWorldState({ discovery_progress: 100 });
        }
    }

    updateStoryDisplay() {
        // 当语言切换时更新故事显示
        if (this.currentStory && window.gameEngine) {
            window.gameEngine.displayScene(this.currentStory);
        }
    }

    // 调试和诊断
    getDebugInfo() {
        return {
            currentStory: this.currentStory,
            storyHistoryLength: this.storyHistory.length,
            choiceHistoryLength: this.choiceHistory.length,
            flagsCount: Object.keys(this.flags).length,
            variablesCount: Object.keys(this.variables).length,
            worldState: this.extendedStoryData.worldState,
            lastChoice: this.choiceHistory[this.choiceHistory.length - 1] || null
        };
    }

    // 重置故事状态
    reset() {
        this.currentStory = null;
        this.storyHistory = [];
        this.choiceHistory = [];
        this.flags = {};
        this.variables = {};
        
        // 重置世界状态
        this.extendedStoryData.worldState = {
            timeline: "original",
            lab_status: "operational", 
            time_anomaly_level: 0,
            discovery_progress: 0
        };
    }
}

// 创建全局故事管理器实例
window.storyManager = new StoryManager();